package com.honeycomb.db.dao.hibernate.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.honeycomb.db.dao.BaseHibernateDao;
import com.honeycomb.db.dao.hibernate.IMapinfoDao;
import com.honeycomb.db.entity.ArticleInfo;
import com.honeycomb.db.entity.MapInfo;
import com.honeycomb.utils.HoneyCombColumnIndicator;
import com.honeycomb.utils.SystemConstants;

public class MapinfoDaoImpl extends BaseHibernateDao<MapInfo, String> implements IMapinfoDao {

	@Override
	public List<ArticleInfo> getArticleinfoListByMapPoint(final double x, final double y, final int distance, final int pageNum) {
		List<ArticleInfo> resultList = null;
		try {
			List articleinfoList = this.getHibernateTemplate().executeFind(new HibernateCallback() {
				@Override
				public Object doInHibernate(Session session) throws HibernateException, SQLException {
					StringBuffer s = new StringBuffer();
					s.append(" from com.honeycomb.db.entity.ArticleInfo ai ");
					s.append(" where ai.mapInfo.mapX > ? and ai.mapInfo.mapX < ? ");
					s.append(" and ai.mapInfo.mapY > ? and ai.mapInfo.mapY < ? ");
					Query query = session.createQuery(s.toString());
					query.setDouble(0, x - distance);
					query.setDouble(1, x + distance);
					query.setDouble(2, y - distance);
					query.setDouble(3, y + distance);
					query.setFirstResult((pageNum - 1) * SystemConstants.PAGING_FOR_MAP_OF_ARTICLE_PAGE_CNT);
					query.setMaxResults(SystemConstants.PAGING_FOR_MAP_OF_ARTICLE_PAGE_CNT);
					return query.list();
				}
			});
			resultList = articleinfoList;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultList;
	}

	@Override
	public int getArticleinfoListByMapPoint_Count(double x, double y, int distance) {
		StringBuffer s = new StringBuffer();
		s.append("from com.honeycomb.db.entity.ArticleInfo ai ");
		s.append("where ai.mapInfo.mapX > ? and ai.mapInfo.mapX < ? ");
		s.append("and ai.mapInfo.mapY > ? and ai.mapInfo.mapY < ? ");
		Object[] val = {x - distance, x + distance, y - distance, y + distance};
		String hqlStr = "select count(*) " + s.toString();
		List list = this.getHibernateTemplate().find(hqlStr, val);
		int count =  ((Long)list.get(0)).intValue();
		return count;
	}
	
	

}
